package org.xxpay.pay.channel.bifpay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.*;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.util.Map;
import java.util.TreeMap;

@Service
public class BifpayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(BifpayPaymentService.class);

    @Override
    public String getChannelName() {
        return BifpayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case BifpayConfig.CHANNEL_NAME_WXPAY_H5 :
                retObj = doPay(payOrder, "wechatwap");
                break;
            default:
                retObj = ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    /**
     *
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder, String type) {
        BifpayConfig bifpayConfig = new BifpayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        Map<String, Object> post= new TreeMap<>();
          post.put("merchantNum", bifpayConfig.getMchId());                                // 订单号
          post.put("orderNo", payOrder.getPayOrderId());                                   // 订单号
          post.put("amount", AmountUtil.convertCent2Dollar(payOrder.getAmount()+""));   // 金额 单位分
          post.put("attch", "");                                                           // 备注
          post.put("ip", payOrder.getClientIp());                                          // IP
          post.put("payType", type);                                                       // 支付节点编码
          post.put("notifyUrl", super.getNotifyUrl(getChannelName(), dbConfig));           // 异步回调地址
          post.put("returnUrl", super.getReturnUrl(getChannelName(), dbConfig));           // 同步回调地址

        try {
            //生成签名
            String sign = MD5Util.string2MD5(bifpayConfig.getMchId()+payOrder.getPayOrderId()+
                    post.get("amount")+post.get("notifyUrl")+bifpayConfig.getKey());
            post.put("sign", sign);
            String postUrl = bifpayConfig.getReqUrl() + "/api/payUrl";
            _log.info("{}请求数据:{}, 请求地址:{}", getChannelName(), post, postUrl);
            String result = BifUtil.post(postUrl, post);
            _log.info("{}返回数据:{}", getChannelName(), result);
            JSONObject jsonObject = JsonUtil.getJSONObjectFromJson(result);
            String code = jsonObject.getString("code");
            if("200".equals(code)) {
                String toPayUrl = jsonObject.getString("payurl");     // 支付URL
                StringBuffer payForm = new StringBuffer();
                payForm.append("<script>window.location.href = '"+toPayUrl+"';</script>");
                retObj.setPayMethod(PayConstant.PAY_METHOD_FORM_JUMP);
                retObj.setJumpInfo(payForm.toString(), toPayUrl);
                int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), toPayUrl, type, updateCount);
                return retObj;
            }else {
                String msg = jsonObject.getString("msg");
                return ApiBuilder.bizError("调起通道失败[通道提示：" + msg +"]");
            }
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("调起通道异常");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        String logPrefix = "【" + getChannelName() + "支付订单查询】";
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询,payOrderId={}", logPrefix, payOrderId);
        return QueryRetMsg.waiting();
    }

}
